<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.w3.org/1999/xhtml">

<head>
    <th:block th:include="common/common_head :: commonHeader('样品申请单')"/>
    <link rel="stylesheet" th:href="@{/static/js/plugins/jquery-layout/jquery.layout-latest.css}">
    <!-- <style type="text/css">.table {table-layout:fixed;}</style> -->
</head>

<body class="gray-bg">

<div class="container-div ui-layout-center">
    <div class="row">
        <div class="col-sm-12 search-condition">
            <form id="sampleRequestItemForm" th:action="@{/sampleRequest/list}" class="form-inline">
                <div class="select-list">
                    <ul>
                        <li class="col-sm-3" style="width: 33%">
                            <label>采购申请单号：</label>
                            <input type="text" name="purchRequestCode" maxlength="10"/>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label>需求日期(起)：</label>
                            <input type="text" name="startDate" id="requestDate" autocomplete="off"/>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label>需求日期(止)：</label>
                            <input type="text" name="endDate" id="deliveryDate" autocomplete="off"/>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label>采购组：</label>
                            <select name="purchGroup" sysDict="CGZ" emptyFirst="true"></select>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label>流程状态：</label>
                            <select id="goodsStatus" name="goodsStatus">
                                <option></option>
                                <option value="-2" selected>未处理</option>
                                <option value="-1">采购申请询价中</option>
                                <option value="4">供应商已报价</option>
                                <option value="0">货源已指定</option>
                                <!--<option value="1">订单已提交</option>-->
                                <option value="2">询价单审批中</option>
                                <option value="3">询价单审批通过</option>
                                <option value="-3">询价单审批驳回</option>
                            </select>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <div>
                                <label>申请人：</label>
                                <input type="text" name="purchRequestStaff"/>
                            </div>
                        </li>
                        <!-- <li class="col-sm-3" style="width: 33%">
                             <div>
                                 <label>样品类型：</label>
                                 <select name="itemType" sysdict="YPLX" emptyFirst="true"> </select>
                             </div>
                         </li>-->
                        <li class="col-sm-3" style="width: 33%">
                            <button id="sampleRequestItemSearchBtn" type="button"
                                    class="btn btn-primary btn-rounded btn-sm"><i class="fa fa-search"></i>&nbsp;搜索
                            </button>
                            <button class="btn btn-warning btn-rounded btn-sm" type="reset"><i class="fa fa-eraser"></i>&nbsp;重置
                            </button>
                            <button id="sampleRequestItemAdvancedSearch" type="button"
                                    class="btn btn-primary btn-rounded btn-sm" style="display: none"><i
                                    class="fa fa-caret-down"></i>&nbsp;高级搜索
                            </button>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="col-sm-12 search-condition titleInfoBar" id="titleInfoBar">
            <span></span>
            <div class="titleInfoBarCloseBtn" title="关闭" onclick="closeTitleInfoBar(this)">&times;</div>
        </div>

        <div class="col-sm-12 select-info order-table">
            <div class="btn-group hidden-xs toolbar" id="sampleRequestItemToolBar" role="group">
                <a class="btn btn-outline btn-danger btn-rounded" onclick="del()"
                   shiro:hasPermission="sampleRequisition:delete">
                    <i class="fa fa-trash-o"></i> 删除
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="add()"
                   shiro:hasPermission="sampleRequisition:add">
                    <i class="fa fa-plus"></i> 新增
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="inquiry()"
                   shiro:hasPermission="sampleRequisition:inquiry">
                    <i class="fa fa-save"></i> 询价
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="supplyGood()" id="goods"
                   data-toggle='modal' data-target=''
                   shiro:hasPermission="sampleRequisition:supplyGood">
                    <i class="fa fa-save"></i> 货源分配
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="changeStatus()"
                   shiro:hasPermission="sampleRequisition:changeStatus">
                    <i class="fa fa-pencil"></i> 修改状态
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="update()">
                    <i class="fa fa-plus"></i> 修改请购单
                </a>
            </div>
            <div style="overflow:auto;">
                <table id="sampleRequestItem" data-mobile-responsive="true"></table>
            </div>
        </div>
    </div>
</div>
<!-- 修改功能 -->
<div id="updateModal" style="display: none">
    <div class="modal-body">
        <div class="row">
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">采购组</span>
                    <select name="purchGroup" sysDict="CGZ" emptyFirst="true" id="purchGroupId"
                            class="form-control"></select>
                </div>
            </div>
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">采购组织</span>
                    <select name="purchOrg" sysDict="CGZZ" emptyFirst="true" id="purchOrgId"
                            class="form-control"></select>
                </div>
            </div>
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">申请人</span>
                    <input name="applier" type="text" id="applierid" class="form-control" readonly>
                </div>
            </div>
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">交货地址</span>
                    <input name="deliveryAddress" type="text" id="deliveryAddressId"
                           class="form-control" autocomplete="off" readonly>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">物料描述</span>
                    <input name="materialDesc" type="text" id="materialDescId"
                           class="form-control" autocomplete="off">
                </div>
            </div>
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">工厂</span>
                    <select name="factory" sysDict="GC" id="factoryId" class="form-control"></select>

                </div>
            </div>
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">物料组</span>
                    <select name="materialGroup" sysdict="WLZ" id="materialGroupId" class="form-control"></select>
                </div>
            </div>
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">申请数量</span>
                    <input name="applyQty" type="number" id="applyQtyId" class="form-control">
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">计量单位</span>
                    <select name="measureUnit" sysDict="JLDW" id="measureUnitId" class="form-control"></select>
                </div>
            </div>
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">成本中心</span>
                    <input name="costCenter" type="text" id="costCenterId"
                           class="form-control" autocomplete="off" readonly>
                </div>
            </div>
            <div class="form-group col-lg-3">
                <div class="input-group">
                    <span class="input-group-addon">需求日期</span>
                    <input name="deliveryDate" type="text" id="deliveryDateId" class="form-control" readonly>
                </div>
            </div>
        </div>

    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" onclick='closeDialog()'>关闭</button>
        <button type="button" class="btn btn-primary" onclick='updateAll()'>确定</button>
    </div>

</div><!-- /.modal-content -->

<!-- 指定报价的供应商 -->
<div class="modal fade" id="myModalVendor" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document" style="width:65%">
        <div class="modal-content" style="height:790px">
            <form id="historicalPriceForm" th:action="@{/historicalPrice/sampleVendorList}" class="form-inline">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">供应商报价信息</h4>
                </div>
                <div class="modal-body" style="height:90%;overflow:auto">

                    <div style="height: 30px;width:100%">
                        <ul>
                            <li class="col-sm-3" style="width: 50%">
                                <label style="width: 150px">供应商SAP编码：</label>
                                <input name="vendorCode" type="text" id="vendorCode" placeholder="供应商SAP编码"
                                       class="form-control">
                            </li>
                            <li class="col-sm-3" style="width: 50%">
                                <label style="width: 150px">供应商名称：</label>
                                <input name="vendorName" type="text" id="vendorName" class="form-control"
                                       placeholder="供应商名称">
                            </li>
                        </ul>
                        <ul>
                            <li class="col-sm-3" style="width: 50%;margin-top: 10px">
                                <label style="width: 150px">物料描述：</label>
                                <input name="materialDesc" type="text" id="materialDesc" class="form-control"
                                       placeholder="物料描述">
                            </li>
                            <li class="col-sm-3" style="width: 50%;margin-top: 10px">
                                <label style="width: 150px">临时供应商SAP编码：</label>
                                <input name="srmCode" type="text" id="srmCode" placeholder="供应商SAP编码"
                                       class="form-control">
                            </li>
                        </ul>
                        <li class="col-sm-3" style="width: 30%;margin-top: 12px">
                            <button id="historicalPriceSearchBtn" type="button"
                                    class="btn btn-primary btn-rounded btn-sm"><i class="fa fa-search"></i>&nbsp;搜索
                            </button>
                            <button class="btn btn-warning btn-rounded btn-sm" type="reset"><i
                                    class="fa fa-eraser"></i>&nbsp;重置
                            </button>
                        </li>
                        </ul>
                    </div>
                    <table class="table table-bordered text-nowrap" id="historicalPrice"></table>
                </div>
            </form>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick='check_form("historicalPrice")'>确定</button>
            </div>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->


<!--引入公共js-->
<div th:include="common/onload_js :: onloadJS"></div>
<script type="text/javascript" th:src="@{/static/js/plugins/jquery-layout/jquery.layout-latest.js}"></script>

<script type="text/javascript">

    $(function () {
        // 初始化时间插件
        laydate.render({elem: '#requestDate'});
        laydate.render({elem: '#deliveryDate'});
        initDictDataSel();//初始化所有字典数据

        /**
         * 查询不同状态请购单条数作为title显示
         */
        var username = parent.$("#susername").text();
        Page.ajaxGET(ctxPath + "/sampleRequest/getCount", null, function (res) {
            var result = res.result;
            var text = username + ",&nbsp;&nbsp;您好!&nbsp;&nbsp;您累计的" + "申请单共有" + result[0] + "条&nbsp;/&nbsp;其中未处理订单" + result[1] + "条&nbsp;/&nbsp;询价中" + result[2] + "条&nbsp;/&nbsp;订单完成" + result[3] + "条";
            showTitleInfoBar($("#titleInfoBar"), text);
        });
    });

    var itemBS = Searcher.createBS('#sampleRequestItem',
        [
            {checkbox: true},
            {title: "采购申请编码", field: "purchRequestCode"},
            {title: "行项目编码", field: "purchRequestItemCode"},
            {
                title: "货源状态", field: "goodsStatus",
                formatter: function (value, row, index) {
                    if (value == -2) {
                        return "未处理";
                    } else if (value == -1) {
                        return "采购申请询价中";
                    } else if (value == 4) {
                        return "供应商已报价";
                    } else if (value == 0) {
                        return "货源已指定";
                    } else if (value == 1) {
                        return "订单已提交";
                    } else if (value == 2) {
                        return "询价单审批中";
                    } else if (value == 3) {
                        return "询价单审批通过";
                    } else if (value == -3) {
                        return "询价单审批驳回";
                    } else {
                        return value;
                    }
                }
            },
            {title: "下单日期", field: "creationDate"},
            {title: "样品类型", field: "itemType"},
            {title: "采购组", field: "purchGroup"},
            {title: "采购组织", field: "purchOrg"},
            {title: "试用次数", field: "reason"},
            {title: "申请人", field: "applier"},
            {title: "物料号", field: "materialCode"},
            {title: "物料描述", field: "materialDesc"},
            {title: "工厂", field: "factory"},
            {title: "库存地点", field: "storageLocation"},
            {title: "物料组", field: "materialGroup"},
            {title: "申请数量", field: "applyQty"},
            {title: "计量单位", field: "measureUnit"},
            {title: "内部订单号", field: "internalOrderCode"},
            {title: "主资产号", field: "mainAssetsCode"},
            //{title: "需求日期",field:"requestDate"},
            {title: "需求日期", field: "deliveryDate"},
            {title: "交货地址", field: "deliveryAddress"},
            {title: "规格", field: "specification"}
        ], {
            pageList: [5, 10, 15, 50, 100], pageSize: 10,
            "showColumns": false, "showRefresh": true, "firstLoad": true
        }
    );

    /*
       * 修改功能
       * */
    function update() {
        var rowDatas = itemBS.getSelectedRows("pkId");

        if (rowDatas.length != 1) {
            Dialog.errorMsg("请选择一行进行修改！");
            return;
        }
        var goodsStatus = itemBS.getSelectedRows("goodsStatus");
        if (goodsStatus != -2) {
            Dialog.errorMsg("不是未处理状态不修改");
            return;
        }
        Dialog.open("详情", $("#updateModal"), {area: ['1024px', '380px']});
        Page.ajaxPOST(ctxPath + "/sampleRequest/findById", {"pkId": rowDatas}, function (res) {
            console.log(res.result);
            var data = JSON.stringify(res.result);
            //json字符串转换成json对象
            var jsonobj = eval('(' + data + ')');
            //获取要循环内的id 内
            getMyModal(true, jsonobj);
        });
    }

    function getMyModal(flg, jsonobj) {
        //获取要循环内的id 内
        var itemEntity = {};
        var inputs = $("#updateModal");
        inputs.each(function (index, input) {
            var its = $(input).find("input");
            its.each(function (idx, it) {
                var inputId = $(it).attr("name");
                if (flg == true) {
                    $(it).val(jsonobj[inputId])
                } else {
                    itemEntity[inputId] = $(it).val();
                }
            });
            //select
            var sels = $(input).find("select");
            sels.each(function (idx, sel) {
                var selName = $(sel).attr("name");
                if (flg == true) {
                    $(sel).val(jsonobj[selName])
                } else {
                    itemEntity[selName] = $(sel).val();
                }
            })
        });
        if (flg == false) {
            data = itemEntity;
        }
    }

    //弹框取消
    function closeDialog() {
        layer.closeAll();
    }

    /*
   * 修改所有
   * */
    function updateAll() {
        var applyQty = $("#applyQtyId").val();
        if (applyQty == null || applyQty == '' || applyQty == 0) {
            Dialog.errorMsg("请修改申请数量！");
            return;
        }
        var rowDatas = itemBS.getSelectedRows("pkId");
        getMyModal(false, null);
        Page.ajaxPOST(ctxPath + "/sampleRequest/updateAll", {
            "pkId": rowDatas[0],
            "data": JSON.stringify(data),
        }, function (res) {
            Dialog.msg(res.msg);
            itemBS.refresh();
            layer.closeAll();
        });
    }

    //刷新数据
    function refresh() {
        itemBS.refresh();
    }

    //弹框取消
    function closeDialog() {
        layer.closeAll();
    }

    /**** 询价********/
    function inquiry() {

        //行项目的id
        var pkId = itemBS.getSelectedRows("pkId");
        var itemrowDatas = $("#sampleRequestItem").bootstrapTable('getSelections');

        if (pkId.length < 1) {
            Dialog.errorMsg("请至少选择一行进行询价！");
            return;
        }
        for (var i = 0; i < itemrowDatas.length; i++) {
            if (itemrowDatas[i].goodsStatus != -2) {
                Dialog.errorMsg("未处理状态才可以询价！");
                return;
            }
        }

        var index = Dialog.openUrl("新增询价单", ctxPath + '/sampleRequest/inquiry/' + pkId,
            {
                area: ['900px', '700px'],
                maxmin: true,
                end: function () {
                }
            });
        layer.full(index)
    }

    /************货源分配******************/
    var searcher1 = '';

    function supplyGood() {
        var rows = $("#sampleRequestItem").bootstrapTable('getSelections');
        if (rows.length >= 1) {
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].goodsStatus == -2) {
                    $("#goods").attr("data-target", "#myModalVendor");
                    //表格控件已生成，取消再次创建
                    if (searcher1) {
                        continue;
                    }
                    searcher1 = Searcher.createBS('#historicalPrice',
                        [
                            {radio: true},
                            {title: "供应商编码", field: "vendorCode"},
                            {title: "临时供应商编码", field: "srmCode"},
                            {title: "供应商名称", field: "vendorName"},
                            {
                                title: "供应商类型", field: "vendorKind",
                                formatter: function (value, row, index) {
                                    var content = '';
                                    if (value == 0) {
                                        content = "正式供应商";
                                    } else if (value == 1) {
                                        content = "临时供应商";
                                    }
                                    return content;
                                }
                            },
                            {title: "物料描述", field: "materialDesc"},
                            {title: "含税单价", field: "price"},
                            {title: "最小起订量", field: "priceUnit"},
                            {title: "币种", field: "currency"},
                            {title: "税码", field: "taxCode"}
                        ], {pageList: [10], pageSize: 10, showColumns: false, showRefresh: false}
                    );
                } else if (rows[i].goodsStatus == 3) {
                    $("#googds").attr("data-target", "");
                    //非生产性物料
                    var rowDatas = itemBS.getSelectedRows("pkId");
                    var requestCode = itemBS.getSelectedRows("purchRequestCode");
                    //purchRequestItemCode
                    if (rowDatas.length < 1) {
                        Dialog.errorMsg("请至少选择一行进行编辑!");
                        return;
                    }
                    // itemBS.getData({'url': ctxPath + '/nproPurchRequestItem/list?purchRequestCode='+row.purchRequestCode});
                    var index = Dialog.openUrl("货源分配信息", ctxPath + '/sampleRequest/toSpecifyAllot/?ids=' + rowDatas + '&requestCode=' + requestCode,
                        {
                            area: ['900px', '700px'],
                            maxmin: true,
                            end: function () {
                            }
                        });
                    layer.full(index)
                } else {
                    $("#goods").attr("data-target", "");
                    if (rows[i].goodsStatus == 0) {
                        return Dialog.alert("货源已经指定 不允许再次货源指定！");
                    }
                    if (rows[i].goodsStatus == -1) {
                        return Dialog.errorMsg("此采购订单询价中不允许货源指定！");
                    }
                    if (rows[i].goodsStatus == 1) {
                        return Dialog.errorMsg("订单价格已提交不允许货源指定！");
                    }
                    if (rows[i].goodsStatus == 2) {
                        return Dialog.errorMsg("订单价格审批中不允许货源指定！");
                    }
                    if (rows[i].goodsStatus == -3) {
                        return Dialog.errorMsg("订单价格审批驳回不允许货源指定！");
                    }
                    if (rows[i].goodsStatus == 4) {
                        return Dialog.errorMsg("订单未比价不允许货源指定！");
                    }

                }
            }
        } else {
            $("#goods").attr("data-target", "");
            Dialog.alert("请选中一行进行货源分配！")
        }
    }

    function check_form(obj) {
        //使用getSelections即可获得，row是json格式的数据
        var rows = $("#" + obj).bootstrapTable('getSelections');
        var rowDatas = [];
        //遍历选中的值
        for (var i = 0; i < rows.length; i++) {
            //historical_price_id
            rowDatas.push(rows[i].viewId);
        }
        //判断是否选中行
        if (!rows || rows.length == 0) {
            Dialog.alert("请先选中一行！");
            return;
        }

        //判断当前选中的供应商是否被冻结
        $.ajax({
            url: ctxPath + '/vendor/sampleCheckFreeze',
            data: {"vendorCode": $("#" + obj).bootstrapTable("getSelections")[0].vendorCode},
            dataType: "json",
            success: function (data) {
                if (data.freeze == 1) {
                    Dialog.errorMsg("该供应商已被冻结，不可选择！");
                    return false;
                } else {
                    showTableData(obj);
                    toEditSampleRequestItem(rowDatas);
                }
            }
        });
    }

    function showTableData(obj) {
        if ("historicalPrice" == obj) {
            $('#myModalVendor').modal('hide');
        }
        if ("ordel" == obj) {
            $('#myModalGoods').modal('hide');
        }
    }


    /**
     * 编辑多条信息
     */
    function toEditSampleRequestItem(rowDatas1) {
        //样品申请行id
        var ids = itemBS.getSelectedRows("pkId");
        if (ids.length < 1) {
            Dialog.errorMsg("至少选择一行进行编辑!");
            return;
        }
        // itemBS.getData({'url': ctxPath + '/nproPurchRequestItem/list?purchRequestCode='+row.purchRequestCode});
        var index = Dialog.openUrl("货源分配信息", ctxPath + '/sampleRequest/toAllot/?ids=' + ids + '&inqids=' + rowDatas1,
            {
                area: ['900px', '700px'],
                maxmin: true,
                end: function () {
                }
            });
        layer.full(index)

    }

    /**
     * 订单驳回后可修改为草稿状态
     */
    function changeStatus() {
        var goodsStatus = itemBS.getSelectedRows("goodsStatus");
        if (goodsStatus.length < 1) {
            Dialog.errorMsg("至少选择一行！");
            return;
        }
        for (var i in goodsStatus) {
            if (goodsStatus[i] != -3) {
                Dialog.errorMsg("非驳回状态不可修改！");
                return;
            }
        }
        var pkIds = itemBS.getSelectedRows("pkId");
        layer.load(1, {shade: [0.3, '#393D49']});
        $.ajax({
            url: ctxPath + "/sampleRequest/changeStatus",
            type: 'POST',
            dataType: "json",
            data: {"pkIds": pkIds},
            cache: false, // 不缓存
            success: function (data) {
                layer.closeAll();
                if (data.code == 500) {
                    Dialog.errorMsg("修改失败！");
                } else {
                    Dialog.msg("操作成功!");
                }
                itemBS.refresh();
            },
            error: function (data) {
                layer.closeAll();
                Dialog.errorMsg("修改失败！");
            }
        });
    }

    /**
     * 新增样品单
     */
    function add() {
        var index = Dialog.openUrl("新增样品单", ctxPath + '/modules/requisition/sample_requisition_add.html', {
            area: ['900px', '700px'],
            maxmin: true,
            end: function () {
            }
        });
        layer.full(index);
    }

    /**
     * 样品单删除
     */
    function del() {
        var row = itemBS.getSelectedRows("pkId");
        var goodsStatus = itemBS.getSelectedRows("goodsStatus");
        if (row.length < 1) {
            Dialog.errorMsg("至少选择一行删除！");
            return;
        }
        for (var i in goodsStatus) {
            if (goodsStatus[i] != -3 || goodsStatus[i] != -2) {
                Dialog.errorMsg("非驳回和草稿状态不可修改！");
                return;
            }
        }
        Dialog.confirm('确定删除？', function () {
            Page.ajaxPOST(ctxPath + "/sampleRequest/deletePkId", {pkId: row}, function () {
                Dialog.msg("操作成功", function () {
                    itemBS.refresh();
                });
            }, {"loadingMsg": "正往服务器提交数据......"});
        });

    }
</script>
</body>
</html>
